package com.design.springboot.booksharing.utils.snowflake;

import java.util.concurrent.atomic.AtomicLong;

/**
 * 雪花算法根据时间戳生成有序的 64 bit 的 Long 类型的唯一 ID
 * <p>
 * 各 bit 含义：
 * <p>
 * 1 bit: 符号位, 0 是正数 1 是负数,  ID 为正数, 所以恒取 0
 * 41 bit: 时间差, 我们可以选择一个参考点, 用它来计算与当前时间的时间差 (毫秒数), 41 bit 存储时间差, 足够使用 69 年
 * 10 bit: 机器码, 能编码 1024 台机器
 * 12 bit: 序列号, 同一机器同一毫秒内产生不同的序列号, 12 bit 可以支持 4096 个序列号
 * 优点：
 * <p>
 * 灵活配置：机器码可以根据需求灵活配置含义
 * 无需持久化：如果序号自增往往需要持久化, 本算法不需要持久化
 * ID 有含义/可逆性：ID 可以反解出来, 对 ID 进行统计分析, 可以很简单的分析出整个系统的繁忙曲线, 还可以定位到每个机器, 在某段时间承担了多少工作, 分析出负载均衡情况
 * 高性能：生成速度很快
 *
 * @author admin
 */
public class Snowflake {

    /**
     * 每一部分所占位数
     */
    private final long unusedBits = 1L;
    private final long timestampBits = 41L;
    private final long systemIdBits = 10L;
    private final long sequenceBits = 12L;

    /**
     * 向左的位移
     */
    private final long timestampShift = sequenceBits + systemIdBits;
    private final long systemIdShift = sequenceBits;

    /**
     * 起始时间戳, 初始化后不可修改
     * 2019-10-01 00:00:00 => 1569859200000L
     */
    private final long startTimestamp = 1569859200000L;

    /**
     * 机器或进程编码, 初始化后不可修改
     * 最大值: 2^10-1 取值范围: [0,1023]
     */
    private final long systemId;

    /**
     * 序列号
     * 最大值: 2^12-1 取值范围: [0,4095]
     */
    private long sequence = 0L;

    /**
     * 上次执行生成 ID 方法的时间戳
     */
    private long lastTimestamp = -1L;

    /**
     * 每一部分最大值
     */
    private final long maxSystemId = ~(-1L << systemIdBits);
    private final long maxSequence = ~(-1L << sequenceBits);

    /**
     * 生成序列号
     */
    public synchronized Long nextId() {
        long currTimestamp = timestamp();

        if (currTimestamp < lastTimestamp) {
            throw new IllegalStateException(
                String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
                    lastTimestamp - currTimestamp));
        }

        if (currTimestamp == lastTimestamp) {
            sequence = (sequence + 1) & maxSequence;
            if (sequence == 0) {
                // overflow: greater than max sequence
                currTimestamp = waitNextMillis(currTimestamp);
            }

        } else {
            // reset to 0 for next period/millisecond
            sequence = 0L;
        }

        // track and memo the time stamp last snowflake ID generated
        lastTimestamp = currTimestamp;

        return ((currTimestamp - startTimestamp) << timestampShift) |
            (systemId << systemIdShift) |
            sequence;
    }

    public Snowflake(long systemId) {
        int minSystemId = 1000;
        if (systemId > maxSystemId || systemId < minSystemId) {
            throw new IllegalArgumentException(
                String.format("system Id can't be greater than %d or less than 1000", maxSystemId + minSystemId));
        }
        this.systemId = systemId - minSystemId;
    }

    /**
     * 追踪调用 waitNextMillis 方法的次数
     */
    private final AtomicLong waitCount = new AtomicLong(0);

    public long getWaitCount() {
        return waitCount.get();
    }

    /**
     * 循环阻塞直到下一秒
     */
    private long waitNextMillis(long currTimestamp) {
        waitCount.incrementAndGet();
        while (currTimestamp <= lastTimestamp) {
            currTimestamp = timestamp();
        }
        return currTimestamp;
    }

    /**
     * 获取当前时间戳
     */
    private long timestamp() {
        return System.currentTimeMillis();
    }
}
